package com.perceptivesoftware.licensing;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.dbcp.BasicDataSourceFactory;
import org.jasypt.util.text.BasicTextEncryptor;

public class TextEncryptUtil extends BasicDataSourceFactory
{
	private static final BasicTextEncryptor cryptor = new BasicTextEncryptor();
	private static final String ENCRYPTION_KEY = "1ff6561f-fd90-3a0d-b3cc-49803450fd8d";

	static
	{
		cryptor.setPassword(ENCRYPTION_KEY);
	}
/**
 *
 * @param encryptedString
 * @return returns null if input is null
 */
	final public static String decode(final String encryptedString)
	{
		if (encryptedString == null)
		{
			return null;
		}
		try
		{
			final String decodedFromHex = new String(Hex.decodeHex(encryptedString.toCharArray()));
			final String decrypted = cryptor.decrypt(decodedFromHex);
			return decrypted;
		}
		catch (final Exception e)
		{
			throw new RuntimeException(e);
		}
	}
/**
 *
 * @param plaintext
 * @return returns null if input is null
 */
	final public static String encode(final String plaintext)
	{
		if (plaintext == null)
		{
			return null;
		}
		final String encryptedString = cryptor.encrypt(plaintext);
		return new String(Hex.encodeHex(encryptedString.getBytes()));
	}
}
